package com.fbli.upload.homework;

import com.fbli.upload.Utils.StreamUtils;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class TCPFileDownloadClient {
    public static void main(String[] args) throws IOException {
        //1.创建客户端连接服务端，得到Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        OutputStream outputStream = socket.getOutputStream();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入下载文件名：");
        String input = scanner.next();
        outputStream.write(input.getBytes());
        socket.shutdownOutput();
        //通过Socket得到输入流
        BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);
        //将得到的bytes数组，写入到指定的路径，就得到一个文件了
        String destFilePath="d:\\"+input+".mp3";
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFilePath));
        bufferedOutputStream.write(bytes);
        System.out.println("下载完成");

        //关闭相关的流
        bufferedOutputStream.close();
        bufferedInputStream.close();
        outputStream.close();
        socket.close();

    }
}
